package com.baidu.speech.qr_code.ui.notifications;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.baidu.speech.qr_code.MainActivity;
import com.baidu.speech.qr_code.R;
import com.baidu.speech.qr_code.ui.Main.MainActivity_son;
import com.bumptech.glide.Glide;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoFragment;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;

import org.litepal.LitePal;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import de.hdodenhof.circleimageview.CircleImageView;

public class NotificationsFragment extends TakePhotoFragment {

    private NotificationsViewModel notificationsViewModel;
    private CircleImageView iv_photo;
    private TextView tv_autograph;
    private Button bu_photograph;
    private Button bu_album;
    //TakePhoto
    private TakePhoto takePhoto;
    private CropOptions cropOptions;  //裁剪参数
    private CompressConfig compressConfig;  //压缩参数
    private Uri imageUri;  //图片保存路径
    private LinearLayout ll_juice;
    private LinearLayout ll_Historical_records;
    private LinearLayout ll_custom_code;
    private LinearLayout ll_Log_out;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_notifications, container, false);
        initView(root);
        //获取弹窗
        return root;
    }

    //当再次运行该程序，刷新以下内容
    @Override
    public void onResume() {
        super.onResume();
        //刷新个性签名
        Personal_signature1 pstv_map = LitePal.findLast(Personal_signature1.class);
        tv_autograph.setText("个性签名:" + pstv_map.getSignature());
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();  //设置压缩、裁剪参数
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        String iconPath = result.getImage().getOriginalPath();
        //Toast显示图片路径
        Toast.makeText(getActivity(), "imagePath:" + iconPath, Toast.LENGTH_SHORT).show();
        //Google Glide库 用于加载图片资源
        Glide.with(getActivity()).load(iconPath).into(iv_photo);
        //把最新图片路径保存在Head_Portrait数据库
        Head_portrait pstv_map1 = new Head_portrait();
        pstv_map1.setHeadshot(iconPath);
        pstv_map1.save();
    }


    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
        Toast.makeText(getActivity(), "Error:" + msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    private void initData() {
        ////获取TakePhoto实例
        takePhoto = getTakePhoto();
        //设置裁剪参数
        cropOptions = new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(false).create();
        //设置压缩参数
        compressConfig = new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(800).create();
        takePhoto.onEnableCompress(compressConfig, true);  //设置为需要压缩
    }

    //获得照片的输出保存Uri
    private Uri getImageCropUri() {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        return Uri.fromFile(file);
    }

    //弹窗
    private void popup() {
        AlertDialog.Builder setDeBugDialog = new AlertDialog.Builder(getActivity());
        View dialogView = LayoutInflater.from(getActivity()).inflate(R.layout.notifications_popup, null);
        bu_photograph = dialogView.findViewById(R.id.bu_photograph);
        bu_photograph.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageUri = getImageCropUri();
                //拍照并裁剪
                takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);
                //仅仅拍照不裁剪
                //takePhoto.onPickFromCapture(imageUri);
            }
        });

        bu_album = dialogView.findViewById(R.id.bu_album);
        bu_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageUri = getImageCropUri();
                //从相册中选取图片并裁剪
                takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                //从相册中选取不裁剪
                //takePhoto.onPickFromGallery();
            }
        });
        setDeBugDialog.setView(dialogView);
        // 点击外部消失弹窗
        setDeBugDialog.setCancelable(true);
        AlertDialog customAlert = setDeBugDialog.show();
    }

    private void initView(View view) {
        ll_Log_out=view.findViewById(R.id.ll_Log_out);
        ll_Log_out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), MainActivity.class));
            }
        });
        ll_custom_code = view.findViewById(R.id.ll_custom_code);
        ll_custom_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), Custom_code.class));
            }
        });
        ll_Historical_records = view.findViewById(R.id.ll_Historical_records);
        ll_juice = view.findViewById(R.id.ll_juice);
        ll_juice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), About_App.class));
            }
        });
        ll_Historical_records.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), Notif_Historical_records.class));
            }
        });
        iv_photo = view.findViewById(R.id.iv_personal_portrait);
        //查看数据库条目
        int size = LitePal.findAll(Head_portrait.class).size();
        Log.d("TAG", "initView" + size);
        //当数据库没有数据时不获取图片，否则报错
        if (size == 0) {
            Toast.makeText(getContext(), "数据库暂时无数据", Toast.LENGTH_SHORT).show();
        } else {
            //获取最新图片
            Head_portrait pstv_map1 = LitePal.findLast(Head_portrait.class);
            //获取Head_portrait数据库最新一张照片显示出来
            File file = new File(pstv_map1.getHeadshot());
            try {
                FileInputStream fil = new FileInputStream(file);
                Bitmap bitmap = BitmapFactory.decodeStream(fil);
                iv_photo.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        iv_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popup();

            }
        });
        tv_autograph = view.findViewById(R.id.tv_autograph);
        int sizetv = LitePal.findAll(Head_portrait.class).size();
        if (sizetv == 0) {
            Personal_signature1 ps1 = LitePal.findLast(Personal_signature1.class);
            tv_autograph.setText(ps1.getSignature());
        }
        tv_autograph.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), Notifications_Personal_signature.class);
                startActivity(intent);
            }
        });
    }

}